package com.dzl.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dzl.base.controller.BaseController;
import com.dzl.base.pojo.BaseData;
import com.dzl.base.service.BaseDataService;
import com.dzl.constant.CommonConstants;
import com.dzl.util.EmptyUtils;
import com.dzl.util.HttpUtil;
import com.dzl.util.JsonResult;
import com.dzl.util.wx.mp.aes.AesException;
import com.dzl.util.wx.mp.aes.WXBizMsgCrypt;
import com.dzl.util.wx.mp.aes.WXMsgUtils;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;

/**
 * 企业微信接收消息控制类
 * @author liuguanjun
 * @date 2021-12-06 14:11:01
 * @return
 **/
@Slf4j
@RestController
@RequestMapping("/receiveEneterpriseWechatMsg")
public class EnterpriseWechatMsgController extends BaseController{

	@Autowired
	private BaseDataService baseDataService;


	/**
	 * 验证URL有效性
	 * @param request msg_signature 企业微信加密签名，msg_signature结合了企业填写的token、请求中的timestamp、nonce参数、加密的消息体
	 * @param request timestamp 时间戳
	 * @param request nonce 随机数
	 * @param request echostr 加密的字符串。需要解密得到消息内容明文，解密后有random、msg_len、msg、CorpID四个字段，其中msg即为消息内容明文
	 * @author liuguanjun
	 * @date 2021-12-06 14:14:27
	 **/
	@GetMapping("")
	public String receiveEneterpriseWechatMsgGet(HttpServletRequest request) throws AesException, IOException {
		String msg_signature = request.getParameter("msg_signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		log.info("ReceiveEneterpriseWechatMsg=================================>msg_signature:"+msg_signature+",timestamp:"+timestamp+",nonce:"+nonce+",echostr:"+echostr);
		String sVerifyMsgSig = URLDecoder.decode(msg_signature,"UTF-8");
		String sVerifyTimeStamp = URLDecoder.decode(timestamp,"UTF-8");
		String sVerifyNonce = URLDecoder.decode(nonce,"UTF-8");
		String sToken = WXMsgUtils.sToken;
		String sCorpID = WXMsgUtils.sCorpID;
		String sEncodingAESKey = WXMsgUtils.sEncodingAESKey;
		WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
		//String sVerifyEchoStr = URLDecoder.decode(echostr,"UTF-8");
		String sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,sVerifyNonce, echostr);
		return sEchoStr;
	}

	/**
	 * 小程序微信客服收发消息
	 * @param request msg_signature 企业微信加密签名，msg_signature结合了企业填写的token、请求中的timestamp、nonce参数、加密的消息体
	 * @param request timestamp 时间戳
	 * @param request nonce 随机数
	 * @author liuguanjun
	 * @date 2021-12-14 16:01:27
	 **/
	@PostMapping("")
	public String receiveEneterpriseWechatMsgPost(HttpServletRequest request) throws AesException, IOException, DocumentException {
		String msg_signature = request.getParameter("msg_signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		//String echostr = request.getParameter("echostr");
		log.info("ReceiveEneterpriseWechatMsg=================================>msg_signature:"+msg_signature+",timestamp:"+timestamp+",nonce:"+nonce);
		String sVerifyMsgSig = URLDecoder.decode(msg_signature,"UTF-8");
		String sVerifyTimeStamp = URLDecoder.decode(timestamp,"UTF-8");
		String sVerifyNonce = URLDecoder.decode(nonce,"UTF-8");
		String sToken = WXMsgUtils.sToken;
		String sCorpID = WXMsgUtils.sCorpID;
		String sEncodingAESKey = WXMsgUtils.sEncodingAESKey;
		WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
		String accessToken = WXMsgUtils.getAccessToken();
		if(EmptyUtils.isEmpty(accessToken)){
			return "";
		}
		//获取加密消息，xml格式请求
		String sReqData = WXMsgUtils.readAsChars(request);
		String sMsg = wxcpt.DecryptMsg(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sReqData);
		String token = "";
		String cursor = "";
		BaseData baseData = baseDataService.findByCode("cursor");
		if(EmptyUtils.isNotEmpty(baseData)){
			cursor = baseData.getValue();
		}
		if(EmptyUtils.isNotEmpty(sMsg)){
			token = WXMsgUtils.getTokenFromXml(sMsg);
		}
		//接收微信消息
		String getMsgUrl = WXMsgUtils.SYNC_MSG_URL.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("cursor",cursor);
		jsonObject.put("token",token);
		jsonObject.put("limit", 1000);
		String getMsgResult = HttpUtil.sendPostUrl(getMsgUrl,jsonObject,"utf-8");
		if(EmptyUtils.isNotEmpty(getMsgResult)){
			JSONObject getMsgResultJson = JSONObject.parseObject(getMsgResult);
			log.info("ReceiveEneterpriseWechatMsg=================================>getMsgResult is "+getMsgResult);
			if(EmptyUtils.isNotEmpty(baseData)){
				baseData.setValue(getMsgResultJson.getString("next_cursor"));
				baseData.setUpdateTime(new Date());
				baseDataService.updateByPrimaryKeySelective(baseData);
			}else{
				baseData = new BaseData();
				baseData.setCode("cursor");
				baseData.setName("微信客服调用接口凭证curson参数");
				baseData.setStatus(CommonConstants.YES);
				baseData.setCreateTime(new Date());
				baseData.setValue(getMsgResultJson.getString("next_cursor"));
				baseData.setUpdateTime(new Date());
				baseDataService.insertSelective(baseData);
			}
			//RedisUtil.set("WX:CURSOR", getMsgResultJson.getString("next_cursor"), 60 * 60 * 2);//缓存2小时
			JSONArray msg_list = getMsgResultJson.getJSONArray("msg_list");
			if(EmptyUtils.isNotEmpty(msg_list)){
				for (Object obj:msg_list) {
					JSONObject msgJsonObject = (JSONObject) obj;
					//发送消息
					String sendMsgUrl = WXMsgUtils.SEND_MSG_URL.replace("ACCESS_TOKEN", accessToken);
					String msgtype = msgJsonObject.getString("msgtype");
					//文本消息或图片语音视频等消息
					if(msgtype.equals("text") || msgtype.equals("image") || msgtype.equals("voice") || msgtype.equals("video") || msgtype.equals("file")|| msgtype.equals("link")|| msgtype.equals("miniprogram")){
						msgJsonObject.put("touser",msgJsonObject.get("external_userid"));
						String sendMsgResult = HttpUtil.sendPostUrl(sendMsgUrl,msgJsonObject,"utf-8");
						log.info("ReceiveEneterpriseWechatMsg=================================>发送消息：touser:"+msgJsonObject.get("external_userid")+",result:"+sendMsgResult);
						if(EmptyUtils.isNotEmpty(sendMsgResult)){
							JSONObject sendMsgResultJsonObject = JSONObject.parseObject(sendMsgResult);
							if(sendMsgResultJsonObject.getInteger("errcode") == 0){
								//获取会话状态
								String getServiceStateUrl = WXMsgUtils.GET_SERVICE_STATE_URL.replace("ACCESS_TOKEN", accessToken);
								JSONObject getServiceStateParam = new JSONObject();
								getServiceStateParam.put("open_kfid",msgJsonObject.get("open_kfid"));
								getServiceStateParam.put("external_userid",msgJsonObject.get("external_userid"));
								String getServiceStateResult = HttpUtil.sendPostUrl(getServiceStateUrl,getServiceStateParam,"utf-8");
								log.info("ReceiveEneterpriseWechatMsg=================================>获取会话状态：getServiceStateResult:"+getServiceStateResult+",service_state:"+getServiceStateParam.get("service_state")+",servicer_userid:"+getServiceStateParam.get("servicer_userid"));
								if(EmptyUtils.isNotEmpty(getServiceStateResult)) {
									JSONObject getServiceStateResultJsonObject = JSONObject.parseObject(getServiceStateResult);
									if (getServiceStateResultJsonObject.getInteger("errcode") == 0) {
										//变更会话状态
										String transServiceStateUrl = WXMsgUtils.TRANS_SERVICE_STATE_URL.replace("ACCESS_TOKEN", accessToken);
										JSONObject transServiceStateParam = new JSONObject();
										transServiceStateParam.put("open_kfid",msgJsonObject.get("open_kfid"));
										transServiceStateParam.put("external_userid",msgJsonObject.get("external_userid"));
										transServiceStateParam.put("service_state", 2);//https://work.weixin.qq.com/api/doc/90000/90135/94669
										transServiceStateParam.put("servicer_userid",getServiceStateResultJsonObject.get("servicer_userid"));
										String transServiceStateResult = HttpUtil.sendPostUrl(transServiceStateUrl,transServiceStateParam,"utf-8");
										log.info("ReceiveEneterpriseWechatMsg=================================>变更会话状态：transServiceStateResult:"+transServiceStateResult+",service_state:"+transServiceStateParam.get("service_state")+",servicer_userid:"+transServiceStateParam.get("servicer_userid"));
									}
								}
							}
						}
					}else if(msgtype.equals("location")){//位置消息

					}else if(msgtype.equals("business_card")){//名片消息

					}else if(msgtype.equals("msgmenu")){//菜单消息

					}else if(msgtype.equals("event")){//事件消息
						String sendMsgOnEventUrl = WXMsgUtils.SEND_MSG_ON_EVENT_URL.replace("ACCESS_TOKEN", accessToken);
						JSONObject sendMsgOnEventParam = new JSONObject();
						if(msgJsonObject.get("event")!=null){
							JSONObject eventJson = (JSONObject) msgJsonObject.get("event");
							String welcome_code = eventJson.getString("welcome_code");
							if(EmptyUtils.isNotEmpty(welcome_code)){
								sendMsgOnEventParam.put("code",welcome_code);
								//sendMsgOnEventParam.put("msgid","");
								sendMsgOnEventParam.put("msgtype","text");
								JSONObject textJson = new JSONObject();
								BaseData welcomeData = baseDataService.findByCode("welcomeMsg");
								if(EmptyUtils.isNotEmpty(welcomeData)){
									textJson.put("content",welcomeData.getValue());
								}else{
									textJson.put("content","欢迎咨询");
								}
								sendMsgOnEventParam.put("text" ,textJson);
								String sendMsgOnEventResult = HttpUtil.sendPostUrl(sendMsgOnEventUrl,sendMsgOnEventParam,"utf-8");
								log.info("ReceiveEneterpriseWechatMsg=================================>发送客服消息：sendMsgOnEventResult:"+sendMsgOnEventResult+",code:"+welcome_code);
								if(EmptyUtils.isNotEmpty(sendMsgOnEventResult)) {

								}
							}
						}

					}
				}
			}
		}
		return "";
	}


	/**
	 * 微信客服自动欢迎语内容详情
	 * @date 2022/01/18 10:50
	 * @author liuguanjun
	 */
	@GetMapping("getWxcustomerWelcomeMsg")
	public JsonResult<String> getWxcustomerWelcomeMsg() {
		BaseData baseData = baseDataService.findByCode("welcomeMsg");
		if(EmptyUtils.isNotEmpty(baseData)){
			return JsonResult.success(baseData.getValue());
		}else{
			return JsonResult.success("你好，很高兴为你服务，请问有什么可以帮到你？");
		}
	}

	/**
	 * 微信客服自动欢迎语修改
	 * @param :content  自动欢迎语内容
	 * @date 2022/01/18 10:50
	 * @author liuguanjun
	 */
	@PostMapping("saveWxcustomerWelcomeMsg")
	public JsonResult<Integer> saveWxcustomerWelcomeMsg(@RequestBody JSONObject param) {
		if(EmptyUtils.isEmpty(param.getString("content"))) {
			return JsonResult.paramErrWithMsg("自动欢迎语不能为空");
		}
		BaseData baseData = baseDataService.findByCode("welcomeMsg");
		if(EmptyUtils.isNotEmpty(baseData)){
			baseData.setValue(param.getString("content"));
			baseData.setUpdateTime(new Date());
			baseDataService.updateByPrimaryKeySelective(baseData);
		}else{
			baseData = new BaseData();
			baseData.setCode("welcomeMsg");
			baseData.setName("企业微信客服自动欢迎语");
			baseData.setStatus(CommonConstants.YES);
			baseData.setCreateTime(new Date());
			baseData.setValue(param.getString("content"));
			baseData.setUpdateTime(new Date());
			baseDataService.insertSelective(baseData);
		}
		return JsonResult.success();
	}


}
